<template>
  <div class="worker-task-header">
    <el-button type="primary" @click="load">加载订单</el-button>
    <el-button type="primary" @click="historyTask">历史订单</el-button>
  </div>
  <div v-if="!showTask &&!showHistoryTask" class="worker-task-none">
    <span>暂无订单</span>
  </div>
  <div v-if="showTask" class="worker-task">
    <el-descriptions title="当前订单详情" :column="3" border size="large">
      <el-descriptions-item label="订单号" width="120px">{{ tableData.num }}</el-descriptions-item>
      <el-descriptions-item label="时间">{{ tableData.date }}</el-descriptions-item>
      <el-descriptions-item label="地点">{{ tableData.position }}</el-descriptions-item>
      <el-descriptions-item label="报修人名字">{{ tableData.name }}</el-descriptions-item>
      <el-descriptions-item label="联系方式">{{ tableData.phone }}</el-descriptions-item>
      <el-descriptions-item label="描述">{{ tableData.description }}</el-descriptions-item>
      <el-descriptions-item label="评论">{{ tableData.comment }}</el-descriptions-item>
      <el-descriptions-item label="订单状态">{{ tableData.state }}</el-descriptions-item>
    </el-descriptions>
  </div>
  <div v-if="showTask" class="worker-task-btn">
    <el-button type="primary" @click="doneTask">完成订单</el-button>
  </div>
  <div v-if="showHistoryTask" class="worker-history-task">
    <span class="title">历史订单</span>
    <div class="table-box">
      <el-table :data="historyData" border style="width: 100%">
        <el-table-column prop="num" label="编号" width="180" />
        <el-table-column prop="date" label="时间" width="180" />
        <el-table-column prop="position" label="地点" />
        <el-table-column prop="name" label="报修人" />
        <el-table-column prop="state" label="状态" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button type="text" @click="handleDetails(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-box">
      <el-pagination v-model:current-page="pageNumber" v-model:page-size="pageSize" :page-sizes="[2, 5, 10, 20]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>
  <DetailsTask ref="detailsTask" />
</template>

<script>
import api from '@/api/axiosConfig';
import moment from 'moment';
import { mapGetters } from 'vuex';
import { ElMessage, ElMessageBox } from "element-plus";
import DetailsTask from '@/components/DetailsTask.vue';

export default {
  name: 'WorkerTask',
  components: {
    DetailsTask,
  },
  computed: {
    ...mapGetters('worker', ['getWorkerId'])
  },
  data() {
    return {
      showTask: false,
      showHistoryTask: false,
      tableData: [],
      historyData: [],
      pageNumber: 1,
      pageSize: 10,
      total: 0,
    }
  },
  methods: {
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getHistoryData();
    },
    handleCurrentChange(pageNumber) {
      this.pageNumber = pageNumber
      this.getHistoryData();
    },
    handleDetails(row) {
      this.$refs.detailsTask.setRow(row)
    },
    historyTask() {
      this.showTask = false;
      this.showHistoryTask = true;
      this.getHistoryData();
    },
    formatDate(date) {
      return moment(date).format('YYYY-MM-DD');
    },
    ChangeState(state) {
      if (state == 0) {
        return "待处理"
      }
      else if (state == 1) {
        return "处理中"
      }
      else if (state == 2) {
        return "已完成"
      }
      else {
        return "未知状态"
      }
    },
    load() {
      this.showHistoryTask = false;
      api.get('/task/worker_search', {
        params: {
          id: this.getWorkerId,
        },
        headers: {
          'Authorization': `Bearer ${this.$store.getters['token/getToken']}`
        }
      })
        .then(res => {
          console.log(res);
          if (res.status == 200) {
            ElMessage.success('加载成功');
          }
          else {
            ElMessage.error('加载失败');
          }
          this.tableData = res.data;
          if (this.tableData == null) {
            this.showTask = false;
          }
          else {
            this.tableData.date = this.formatDate(this.tableData.date);
            this.tableData.state = this.ChangeState(this.tableData.state);
            this.showTask = true;
          }
        }).catch(error => {
          console.log(error);
        });
    },
    getHistoryData() {
      api.get('/task/worker_history_task', {
        params: {
          id: this.getWorkerId,
          pageNum: this.pageNumber,
          pageSize: this.pageSize,
        },
        headers: {
          'Authorization': `Bearer ${this.$store.getters['token/getToken']}`
        }
      })
        .then(res => {
          console.log(res);
          if (res.status == 200) {
            ElMessage.success('加载成功');
          }
          else {
            ElMessage.error('加载失败');
          }
          this.total = res.data.total;
          this.historyData = res.data.records.map(item => {
            item.date = this.formatDate(item.date);
            item.state = this.ChangeState(item.state);
            return item;
          });
        }).catch(error => {
          console.log(error);
        });
    },
    setWorkerFree() {
      api.put('/worker/free',
        null,
        {
          params: {
            id: this.getWorkerId,
          },
          headers: {
            'Authorization': `Bearer ${this.$store.getters['token/getToken']}`
          }
        }
      ).then(res => {
        console.log(res);
        ElMessage({
          message: '释放成功',
          type: 'info',
        })
      }).catch(err => {
        console.log(err);
        ElMessage({
          message: '释放失败',
          type: 'warning',
        })
      });
    },
    doneTask() {
      ElMessageBox.confirm('确认完成该订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.put('/task/confirm',
          null,
          {
            params: {
              num: this.tableData.num,
            },
            headers: {
              'Authorization': `Bearer ${this.$store.getters['token/getToken']}`
            },
          },
        ).then(res => {
          ElMessage.success('订单完成成功');
          console.log(res);
          this.setWorkerFree();
          this.load();
        }).catch(error => {
          ElMessage.error('订单完成失败');
          console.log(error);
        });
      }).catch(() => {
        ElMessage.info('已取消');
      });
    }
  },
  created() {
    this.load();
  }
}

</script>

<style scoped>
.worker-task-none {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
}
.worker-task-btn {
  margin-top: 20px;
  display: flex;
  justify-content: right;
}

.worker-task-header {
  display: flex;
  justify-content: left;
  margin-bottom: 20px;
}

.worker-history-task {
  margin-top: 20px;

  .title {
    display: flex;
    justify-content: left;
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
  }
}
</style>
